﻿using System;
using System.Configuration;
using System.Net.Mail;
using System.Web.UI;
using CurriculumData;

namespace CurriculumSite
{
    public partial class RegistrationWebUserControl : UserControl
    {
        #region Members

        private readonly Controller _controller = new Controller();

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            var candidate = (Candidate)Session["Candidate"];
            if (candidate != null)
                passwordASPxLabel.Text = "*" + candidate.Password;
        }

        #region Event Handlers

        protected void registerASPxButton_Click(object sender, EventArgs e)
        {
            var candidate = _controller.CreateCandidate(taxNumberASPxTextBox.Text, emailASPxTextBox.Text);
            if (candidate == null)
            {
                passwordASPxLabel.Text = "!Este número de contribuinte já se encontra registado. Se perdeu a sua password, por favor, dirija-se aos serviços para solicitar nova password.";
                return;
            }
            Session["Candidate"] = candidate;
            passwordASPxLabel.Text = "*" + candidate.Password;
            if (emailASPxTextBox.Text == String.Empty)
                return;
            var mailmessage = new MailMessage { From = new MailAddress(ConfigurationManager.AppSettings["EmailAddress"], ConfigurationManager.AppSettings["EmailName"]) };
            mailmessage.To.Add(new MailAddress(candidate.Email, candidate.CandidateName));
            mailmessage.Subject = ConfigurationManager.AppSettings["EmailSubject"];
            mailmessage.Body = String.Format(ConfigurationManager.AppSettings["EmailBody"], candidate.CandidateName, candidate.Password);
            mailmessage.IsBodyHtml = true;
            var smtpClient = new SmtpClient();
            smtpClient.Send(mailmessage);
        }

        #endregion
    }
}